<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CTaskForm">
          <a-row>
						<a-col :span="12">
							<a-form-item label="任务名称" v-bind="validateInfos.name" id="CTaskForm-name" name="name">
								<a-input :disabled="disabledFlag" v-model:value="formData.name" placeholder="请输入任务名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="项目名称" v-bind="validateInfos.projectName" id="CTaskForm-projectName" name="projectName">
								<a-input :disabled="disabledFlag" v-model:value="formData.projectName" placeholder="请输入项目名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="主项目" v-bind="validateInfos.projectId" id="CTaskForm-projectId" name="projectId">
								<a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.projectId"
                  :showSearch="true"
                  :options="projectList"
                  optionFilterProp="label"

                ></a-select>
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="任务日期" v-bind="validateInfos.taskDate" id="CTaskForm-taskDate" name="taskDate">
                <a-date-picker :disabled="disabledFlag" placeholder="请选择任务日期"  v-model:value="formData.taskDate" value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="任务类型" v-bind="validateInfos.type" id="CTaskForm-type" name="type">

                <j-dict-select-tag  :disabled="disabledFlag"  v-model:value="formData.type" dictCode="task_type" placeholder="请输入任务类型"  allow-clear />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="联系人" v-bind="validateInfos.contactPerson" id="CTaskForm-contactPerson" name="contactPerson">
                <a-input :disabled="disabledFlag" v-model:value="formData.contactPerson" placeholder="请输入联系人"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="联系电话" v-bind="validateInfos.phone" id="CTaskForm-phone" name="phone">
                <a-input :disabled="disabledFlag" v-model:value="formData.phone" placeholder="请输入联系电话"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
						<a-col :span="12">
							<a-form-item label="任务地址" v-bind="validateInfos.address" id="CTaskForm-address" name="address">
								<a-textarea :disabled="disabledFlag" v-model:value="formData.address" :rows="4" placeholder="请输入任务地址" />
							</a-form-item>
						</a-col>

						<a-col :span="12">
							<a-form-item label="任务内容描述" v-bind="validateInfos.content" id="CTaskForm-content" name="content">
								<a-textarea :disabled="disabledFlag" v-model:value="formData.content" :rows="4" placeholder="请输入任务内容描述" />
							</a-form-item>
						</a-col>

						<a-col :span="12">
							<a-form-item label="项目地点" v-bind="validateInfos.projectSite" id="CTaskForm-projectSite" name="projectSite">
								<a-textarea :disabled="disabledFlag" v-model:value="formData.projectSite" :rows="4" placeholder="请输入项目地点" />
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="情况图片视频" v-bind="validateInfos.situationMedia" id="CTaskForm-situationMedia" name="situationMedia">
                <j-upload :disabled="disabledFlag" v-model:value="formData.situationMedia"   ></j-upload>
              </a-form-item>
            </a-col>

            <a-divider  v-auth="'crm:task:assigntasks'" >指派信息</a-divider >
            <a-col :span="24" v-auth="'crm:task:assigntasks'">
              <a-form-item label="分配给谁" v-bind="validateInfos.assignedTo" id="CSubProjectForm-assignedTo" name="assignedTo">
                 <j-dict-select-tag showSearch="true"  :disabled="disabledFlag" v-model:value="formData.assignedTo" dictCode="sys_user,username,id" placeholder="请输入分配给谁"  allow-clear />
              </a-form-item>
            </a-col>

            <a-divider v-if="formData.id">处理结果</a-divider >
            <a-col :span="12" v-if="formData.id">
							<a-form-item label="处理日期" v-bind="validateInfos.processingDate" id="CTaskForm-processingDate" name="processingDate">
								<a-date-picker placeholder="请选择处理日期"  v-model:value="formData.processingDate" value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12" v-if="formData.id">
							<a-form-item label="处理结果描述" v-bind="validateInfos.processingResult" id="CTaskForm-processingResult" name="processingResult">
								<a-textarea v-model:value="formData.processingResult" :rows="4" placeholder="请输入处理结果描述" />
							</a-form-item>
						</a-col>
						<a-col :span="12" v-if="formData.id">
							<a-form-item label="处理附件" v-bind="validateInfos.attachment" id="CTaskForm-attachment" name="attachment">
								<j-upload v-model:value="formData.attachment"  dragger="true"  :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }" ></j-upload>
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../CTask.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';

    import { getContractorList, getProjectList, getSubProjectList ,getQueryByProjectId} from '@/views/common.api';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const disabledFlag = ref(false);
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    name: '',   
    projectName: '',   
    projectId: '',   
    address: '',   
    taskDate: '',   
    content: '',   
    type: '',   
    projectSite: '',   
    contactPerson: '',   
    phone: '',   
    situationMedia: '',   
    assignedTo: '',   
    processingDate: '',   
    processingResult: '',   
    attachment: '',   
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    assignedTo: [{ required: true, message: '请输入指派给谁!'},],
    processingDate: [{ required: true, message: '请输入处理时间!'},],
    processingResult: [{ required: true, message: '请输入处理描述!'},],
    attachment: [{ required: true, message: '请输入处理附件!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
    disabledFlag.value = false;
    if(record.id){
      disabledFlag.value = true;
    }
  }
  async function projectOnChange(value){
    formData.address =""
    formData.projectSite =""
    formData.contactPerson =""
    formData.phone =""

    const param = {"projectId":value}
    const data =  await getQueryByProjectId(param)
    debugger
    if(data != undefined){
      let address =""
      if(data.city != undefined && data.city != null){
        address += data.city.replaceAll("/","");
      }
      if(data.address != undefined && data.address != null){
        address += data.address
      }
      formData.address =  address
      formData.projectSite =  address

      if(data.managerName != undefined && data.managerName != null){
        formData.contactPerson =  data.managerName
      }

      if(data.managerPhone != undefined && data.managerPhone != null){
        formData.phone =  data.managerPhone
      }


    }
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        for(var i = 0; i < errorFields.length; i++) {
          const firstField = errorFields[i];
          if(firstField.errors.includes("指派给谁")){
            formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
            return Promise.reject(errorFields);
          }else if(formData.id.length > 0){//修改
            formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
            return Promise.reject(errorFields);
          }
        }
      }

    }


    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  /**
   * 加载 主项目下拉
   */
  const projectList = ref([])
  async function loadProjectList(){
    projectList.value = []
    projectList.value = await getProjectList()
  }
 onMounted(async () => {
   loadProjectList()
 })

  defineExpose({
    add,
    edit,
    submitForm,
    projectOnChange,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
